package com.andy.ui.base;

import android.content.Context;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.andy.ui.R;
import com.andy.ui.widget.PageStateView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.trello.rxlifecycle3.android.FragmentEvent;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * @Author: luofan
 * @CreateDate: 2020/3/23 15:42
 * @Description: M是json解析结果, B是adapter的item
 */
public abstract class BaseListFragment<M, B> extends BasePageStateFragment {

    private static final String TAG = "BaseListFragment";

    protected BaseQuickAdapter<B, BaseViewHolder> mAdapter;

    private SmartRefreshLayout mRefreshLayout;

    private RecyclerView mRecyclerView;

    private boolean mIsMutiPage = true;

    private int mDefaultPageNum = 0;

    private int mPageNum = mDefaultPageNum;

    private int mPageSize = 20;

    private boolean mAutoRequest = true;

    @Override
    public void initView() {
        if (getContext() == null) {
            Log.e(TAG, "getContext is null, cant not initView");
            return;
        }
        mAdapter = getAdapter();
        mRecyclerView = getRecyclerView();
        mRecyclerView.setLayoutManager(getLayoutManager(getContext()));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter);
        if (getRefreshLayout() != null) {
            mRefreshLayout = getRefreshLayout();
            initRefreshLayout();
        }
        getPageStateView().getErrorView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestData(true);
            }
        });
    }

    public void setAutoRequest(boolean autoRequest) {
        mAutoRequest = autoRequest;
    }

    @Override
    public void initLogic() {
        requestData(mAutoRequest);
    }

    public void setDefaultPageNum(int defaultPageNum) {
        mDefaultPageNum = defaultPageNum;
    }

    public void setPageNum(int pageNum) {
        mPageNum = pageNum;
    }

    public void setPageSize(int pageSize) {
        mPageSize = pageSize;
    }

    public int getPageNum() {
        return mPageNum;
    }

    public void setMutiPage(boolean mutiPage) {
        mIsMutiPage = mutiPage;
    }

    /**
     * @return 获取网络请求Observable
     */
    @NonNull
    protected abstract Observable<M> getObservable();

    /**
     * 从结果中获取recycler需要的列表数据
     *
     * @param response
     * @return
     */
    @NonNull
    protected abstract List<B> getRecyclerDataFromResult(M response);

    protected void requestData(boolean showLoadingView) {
        getObservable().compose(bindUntilEvent(FragmentEvent.DETACH))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<M>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        if (showLoadingView) {
                            getPageStateView().showViewByState(PageStateView.STATE_LOADING);
                        }
                    }

                    @Override
                    public void onNext(M result) {
                        onGetData(result);
                    }

                    @Override
                    public void onError(Throwable e) {
                        getPageStateView().showViewByState(PageStateView.STATE_ERROR);
                        onGetError(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    protected void onGetData(M result) {
        if (mRecyclerView.getItemDecorationCount() == 0) {
            RecyclerView.ItemDecoration decoration = getItemDecoration();
            if (decoration != null) {
                mRecyclerView.addItemDecoration(decoration);
            }
        }
        List<B> list = getRecyclerDataFromResult(result);
        if (list.size() > 0) {
            getPageStateView().showViewByState(PageStateView.STATE_CONTENT);
        } else {
            getPageStateView().showViewByState(PageStateView.STATE_EMPTY);
        }
        if (mRefreshLayout != null) {
            if (list.size() > 0) {
                mRefreshLayout.setEnableLoadMore(true);
                mRefreshLayout.setEnableAutoLoadMore(true);
            }
            if (mPageNum == mDefaultPageNum) {
                mRefreshLayout.finishRefresh();
            } else {
                if (mIsMutiPage) {
                    if (list.size() == mPageSize) {
                        mRefreshLayout.finishLoadMore();
                    } else {
                        mRefreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }
            }
        }
        initRecyclerData(list);
    }

    protected void initRecyclerData(List<B> list) {
        if (mIsMutiPage) {
            if (mPageNum == mDefaultPageNum) {
                mAdapter.replaceData(list);
            } else {
                mAdapter.addData(list);
            }
        } else {
            mAdapter.replaceData(list);
        }
    }

    protected void onGetError(Throwable e) {
        if (mRefreshLayout != null) {
            mRefreshLayout.finishRefresh();
        }
    }

    private void initRefreshLayout() {
        mRefreshLayout.setEnableLoadMore(false);
        //这里需要先做加载更多屏蔽
        mRefreshLayout.setEnableAutoLoadMore(false);
        mRefreshLayout.setOnRefreshListener(refreshlayout -> {
            mRecyclerView.scrollToPosition(0);
            mPageNum = mDefaultPageNum;
            requestData(false);
        });
        mRefreshLayout.setOnLoadMoreListener(refreshlayout -> {
            mPageNum++;
            requestData(false);
        });
    }

    /**
     * @return 获取recyclerView
     */
    @NonNull
    protected abstract RecyclerView getRecyclerView();

    /**
     * @return 获取刷新view
     */
    @Nullable
    protected abstract SmartRefreshLayout getRefreshLayout();

    @NonNull
    protected abstract BaseQuickAdapter<B, BaseViewHolder> getAdapter();

    protected RecyclerView.ItemDecoration getItemDecoration() {
        DividerItemDecoration decoration = new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
        decoration.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.shape_divider_1px));
        return decoration;
    }

    @NonNull
    protected RecyclerView.LayoutManager getLayoutManager(Context context) {
        return new LinearLayoutManager(context);
    }
}
